<template>
  <div class="transfer-add-container">
    <!-- 门仓选择区域 -->
    <el-form :inline="true" class="store-select-form" style="display: flex; justify-content: space-between">
      <div>
        <el-form-item label="调出门仓:">
          <!-- <el-select v-model="outStore" placeholder="请选择调出门仓" style="width: 180px">
          <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select> -->
          <el-cascader
            v-model="transferOutStoreId"
            :options="storeList"
            :props="{ expandTrigger: 'hover', value: 'id', label: 'name' }"
            @change="handleTransferOutStoreChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="调入门仓:">
          <el-cascader
            ref="transferInStore"
            v-model="transferInStoreId"
            :options="storeList"
            :props="{ expandTrigger: 'hover', value: 'id', label: 'name' }"
            @change="handleTransferInStoreChange"
          ></el-cascader>
        </el-form-item>
      
      <!-- {{transferTableDataWithAdd}} -->
        <el-form-item label="单据时间:"  prop="receiptTime">
          <!-- <el-input v-model="receiptTime" placeholder="请选择单据时间" /> -->
          <el-date-picker v-model="receiptTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="调货原因:">
          <el-input v-model="remarks" placeholder="请输入调货原因" />
        </el-form-item>
      </div>
      <div>

        <el-form-item>
          <el-button type="primary" @click="submitted" :disabled="transferTableDataWithAdd.length == 0"
            >提交审核</el-button
          >
        </el-form-item>
      </div>
    </el-form>
    <!-- 调拨单表格 -->
    <div class="transfer-table-wrapper">
        <div style="display: flex; justify-content: flex-start; margin-bottom: 10px;">
          <el-button type="primary" @click="addProduct" :disabled="!transferOutStoreId || !transferInStoreId"
            >添加商品</el-button
          >
        </div>
      <el-table :data="transferTableDataWithAdd" border stripe size="small">
        <el-table-column prop="index" label="序号" width="60" align="center">
          <template slot-scope="scope">
            <span v-if="!scope.row.isAdd">{{ (scope.$index + 1) | padIndex }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="商品名称" align="center">
          <template slot-scope="scope">
            <span v-if="!scope.row.isAdd">{{ scope.row.productName }}</span>
            <span v-else class="add-row-cell">
              <el-button
                type="dashed"
                icon="el-icon-plus"
                @click="addProduct"
                class="add-product-btn"
                :disabled="!transferOutStoreId || !transferInStoreId"
                >添加商品</el-button
              >
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="image" label="图片" align="center" width="70">
          <template slot-scope="scope">
            <img
              v-if="!scope.row.isAdd"
              :src="scope.row.image"
              alt=""
              style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px; border: 1px solid #eee"
            />
          </template>
        </el-table-column>
        <el-table-column prop="sku" label="商品规格" align="center">
          <template slot-scope="scope">
            <span v-if="!scope.row.isAdd">{{ scope.row.sku }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="productAttrValueId" label="商品编码" align="center">
          <template slot-scope="scope">
            <span v-if="!scope.row.isAdd">{{ scope.row.productAttrValueId }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="unitName" label="单位" align="center" width="60">
          <template slot-scope="scope">
            <span v-if="!scope.row.isAdd">{{ scope.row.unitName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="单价" align="center">
          <template slot-scope="scope">
            <span v-if="!scope.row.isAdd">{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="transferOutStoreThenStock" label="调出门仓库存" align="center">
          <template slot-scope="scope">
            <span v-if="!scope.row.isAdd">{{ scope.row.transferOutStoreThenStock }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="number" label="调拨数量" align="center">
          <template slot-scope="scope">
            <el-input-number
              v-if="!scope.row.isAdd"
              v-model="scope.row.number"
              :min="1"
              :max="scope.row.transferOutStoreThenStock"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column prop="transferInStoreThenStock" label="调入门仓库存" align="center">
          <template slot-scope="scope">
            <span v-if="!scope.row.isAdd">{{ scope.row.transferInStoreThenStock || 0 }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="remark" label="备注" align="center">
          <template slot-scope="scope">
            <el-input v-if="!scope.row.isAdd" v-model="scope.row.remark" size="small" placeholder="请输入备注" />
          </template>
        </el-table-column> -->
        <el-table-column label="操作" align="center" width="100">
          <template slot-scope="scope">
            <div v-if="!scope.row.isAdd" style="display: flex; justify-content: center; align-items: center">
              <!-- <el-button type="text" size="small" @click="handleRowAdd(scope.$index)">+</el-button> -->
              <el-button type="text" size="small" @click="handleRowRemove(scope.$index)" style="color: red;">移除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-drawer
      title="请选择商品"
      :visible.sync="showDrawer"
      size="60%"
      direction="rtl"
      :before-close="handleDrawerClose"
      custom-class="product-drawer"
    >
      <div class="drawer-content-flex">
        <!-- 分类树结构 -->
        <div class="category-tree-panel">
          <el-tree
            :data="categoryTree"
            :props="treeProps"
            node-key="id"
            highlight-current
            @node-click="handleCategoryClick"
            default-expand-all
          />
        </div>
        <!-- 商品列表区域 -->
        <div class="product-list-panel">
          <div class="product-list-header">
            <el-input
              v-model="searchKeyword"
              placeholder="请输入商品名称"
              style="width: 220px; margin-right: 10px"
              @keyup.enter.native="fetchProductList"
              clearable
            />
            <el-button @click="fetchProductList" size="small" type="primary">搜索</el-button>
          </div>
          <el-table
            :data="productList"
            @selection-change="handleSelectionChange"
            style="width: 100%; margin-top: 10px"
            ref="productTable"
            border
            size="small"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column prop="productName" label="商品名称" align="center" />
            <el-table-column prop="image" label="图片" align="center" width="70">
              <template slot-scope="scope">
                <img
                  :src="scope.row.image"
                  alt=""
                  style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px; border: 1px solid #eee"
                />
              </template>
            </el-table-column>
            <el-table-column prop="sku" label="商品规格" align="center" />
            <el-table-column prop="productAttrValueId" label="商品编码" align="center" />
            <el-table-column prop="price" label="单价" align="center" />
            <el-table-column prop="transferOutStoreThenStock" label="库存" align="center" />  
          </el-table>
          <el-pagination
            :current-page="page"
            :page-size="pageSize"
            :total="total"
            @current-change="handlePageChange"
            layout="total, prev, pager, next"
            style="margin-top: 10px; text-align: right"
          />
          <div class="drawer-footer-btns">
            <el-button @click="handleDrawerClose">取消</el-button>
            <el-button type="primary" @click="handleBatchAdd">批量添加</el-button>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
// 树形结构列表
import { productCategoryListApi } from '@/api/product';
import { listStore, listProductSpec, transferOrderSave, transferOrderInfo } from '@/api/commercial';
export default {
  data() {
    return {
      showDrawer: false,
      searchKeyword: '',
      productList: [],
      selectedProducts: [],
      page: 1,
      pageSize: 10,
      total: 0,
      transferProducts: [],
      // 门仓选择相关
      transferOutStoreId: '',
      transferInType: '', //转入类型(1仓库 2门仓)
      transferOutType: '', //转出类型(1仓库 2门仓)
      transferInStoreId: '',
      storeList: [
        { name: '仓库', id: 1, children: [] },
        { name: '门仓', id: 2, children: [] },
      ],
      // 分类树相关
      categoryTree: [
        {
          id: 0,
          label: '全部',
          children: [
            {
              id: 1,
              label: '女装',
              children: [
                { id: 11, label: '上衣' },
                { id: 12, label: '下衣' },
              ],
            },
            {
              id: 2,
              label: '男装',
              children: [
                { id: 21, label: '上衣' },
                { id: 22, label: '下衣' },
              ],
            },
          ],
        },
      ],
      treeProps: {
        children: 'children',
        label: 'label',
      },
      selectedCategoryId: '',
      transferTableData: [],
      remarks: '',
      receiptTime: new Date(), //获取当天时间回显
      IsreadOnly: false,
      // 扫描仪输入相关
      scannerBuffer: '',
      scannerTimeout: null,
      scannerDelay: 100, // 扫描仪输入延迟时间(ms)
      lastKeyTime: 0, // 上次按键时间
      keyPressCount: 0, // 按键次数
      isProcessingScanner: false, // 是否正在处理扫描仪输入
      scannerStartTime: 0, // 扫描开始时间
    };
  },
  created() {
    this.getStoreList();
  },
  mounted() {
    // this.getStoreList();
    // console.log(this.$route.query,280);
    // if(this.$route.query.id){
    //   this.getTransferOrderDetail(this.$route.query.id);
    //   this.IsreadOnly = true;
    // }
    //检测扫描仪输入
    this.initScannerInput();
  },
  beforeDestroy() {
    this.removeScannerInput();
  },
  methods: {
    getTransferOrderDetail(id){
      transferOrderInfo({id:id}).then((res) => {
        console.log(res,288);
        this.transferTableData = res.list || [];
      });
    },
    initScannerInput() {
      // 初始化扫描仪输入监听
      this.scannerBuffer = '';
      this.scannerTimeout = null;
      this.lastKeyTime = 0;
      this.keyPressCount = 0;
      this.isProcessingScanner = false;
      this.scannerStartTime = 0;
      
      // 添加全局键盘事件监听
      document.addEventListener('keydown', this.handleScannerInput);
      
      // 防止页面失去焦点时停止监听
      window.addEventListener('focus', this.handleWindowFocus);
      window.addEventListener('blur', this.handleWindowBlur);
    },
    
    removeScannerInput() {
      // 移除事件监听
      document.removeEventListener('keydown', this.handleScannerInput);
      window.removeEventListener('focus', this.handleWindowFocus);
      window.removeEventListener('blur', this.handleWindowBlur);
      
      // 清除定时器
      if (this.scannerTimeout) {
        clearTimeout(this.scannerTimeout);
        this.scannerTimeout = null;
      }
    },
    
    handleScannerInput(event) {
      // 处理扫描仪输入
      const key = event.key;
      
      // 检查是否有输入框处于焦点状态
      const activeElement = document.activeElement;
      const isInputFocused = activeElement && (
        activeElement.tagName === 'INPUT' ||
        activeElement.tagName === 'TEXTAREA' ||
        activeElement.contentEditable === 'true' ||
        activeElement.classList.contains('el-input__inner') ||
        activeElement.classList.contains('el-textarea__inner') ||
        activeElement.classList.contains('el-select') ||
        activeElement.closest('.el-select') ||
        activeElement.closest('.el-date-picker')
      );
      
      // 如果输入框有焦点，不处理扫描仪输入
      if (isInputFocused) {
        console.log('输入框有焦点，忽略扫描仪输入');
        return;
      }
      
      // 如果正在处理扫描仪输入，忽略新的输入
      if (this.isProcessingScanner) {
        console.log('正在处理扫描仪输入，忽略新输入');
        return;
      }
      
      const currentTime = Date.now();
      
      // 如果是回车键，处理扫描结果
      if (key === 'Enter') {
        event.preventDefault();
        this.processScannerInput();
        return;
      }
      
      // 如果是可打印字符，添加到缓冲区
      if (key.length === 1 && key.charCodeAt(0) >= 32) {
        // 记录扫描开始时间
        if (this.scannerBuffer === '') {
          this.scannerStartTime = currentTime;
          this.keyPressCount = 0;
        }
        
        this.scannerBuffer += key;
        this.keyPressCount++;
        
        // 清除之前的定时器
        if (this.scannerTimeout) {
          clearTimeout(this.scannerTimeout);
        }
        
        // 设置新的定时器，模拟扫描仪输入完成
        this.scannerTimeout = setTimeout(() => {
          this.processScannerInput();
        }, this.scannerDelay);
      }
      
      this.lastKeyTime = currentTime;
    },
    
    processScannerInput() {
      if (!this.scannerBuffer.trim() || this.isProcessingScanner) {
        return;
      }
      
      // 设置处理标志，防止重复处理
      this.isProcessingScanner = true;
      
      const scannedCode = this.scannerBuffer.trim();
      console.log('扫描仪输入:', scannedCode);
      
      // 检查扫描码长度，通常条码长度在8-20位之间
      if (scannedCode.length < 8 || scannedCode.length > 20) {
        console.log('扫描码长度不符合条码特征，忽略输入');
        this.resetScannerBuffer();
        return;
      }
      
      // 检查是否为纯数字条码（常见条码类型）
      const isNumericBarcode = /^\d+$/.test(scannedCode);
      if (!isNumericBarcode) {
        console.log('非数字条码，可能是手动输入，忽略');
        this.resetScannerBuffer();
        return;
      }
      
      // 检查输入速度，扫描仪输入通常很快（总时间小于500ms）
      const totalInputTime = this.lastKeyTime - this.scannerStartTime;
      console.log(totalInputTime,328);
      if (totalInputTime > 800) {
        console.log('输入时间过长，可能是手动输入，忽略');
        this.resetScannerBuffer();
        return;
      }
      
      // 检查按键间隔，扫描仪输入间隔通常很短
      const avgInterval = totalInputTime / this.keyPressCount;
      console.log(avgInterval,332);
      if (avgInterval > 60) {
        console.log('按键间隔过长，可能是手动输入，忽略');
        this.resetScannerBuffer();
        return;
      }
      
      // 处理扫描的商品编码
      this.handleScannedProductCode(scannedCode);
    },
    
    resetScannerBuffer() {
      // 重置扫描仪缓冲区
      this.scannerBuffer = '';
      this.keyPressCount = 0;
      this.lastKeyTime = 0;
      this.scannerStartTime = 0;
      this.isProcessingScanner = false;
      
      // 清除定时器
      if (this.scannerTimeout) {
        clearTimeout(this.scannerTimeout);
        this.scannerTimeout = null;
      }
    },
    
    handleScannedProductCode(productCode) {
      // 根据商品编码查找商品
      if (!this.transferOutStoreId || !this.transferInStoreId) {
        this.$message.warning('请先选择调出门仓和调入门仓');
        this.resetScannerBuffer();
        return;
      }
      
      // 构造查询参数
      const params = {
        barCode: productCode,
        limit: 1,
        page: 1,
        transferOutStoreId: this.transferOutStoreId[1],
        transferOutType: this.transferOutType,
        transferInStoreId: this.transferInStoreId[1],
        transferInType: this.transferInType,
      };
      
      // 查询商品
      listProductSpec(params).then((res) => {
        console.log(res,397);
        if (res && res.list && res.list.length > 0) {
          const product = res.list[0];
          
          // 检查商品是否已存在
          const existingIndex = this.transferTableData.findIndex(
            item => item.productAttrValueId === product.productAttrValueId
          );
          
          if (existingIndex >= 0) {
            // 商品已存在，增加数量
            const currentItem = this.transferTableData[existingIndex];
            if (currentItem.number < currentItem.transferOutStoreThenStock) {
              currentItem.number += 1;
              this.$message.success(`商品 ${product.productName} 数量已增加`);
            } else {
              this.$message.warning(`商品 ${product.productName} 库存不足`);
            }
          } else {
            // 添加新商品
            product.number = 1; // 默认数量为1
            this.transferTableData.push(product);
            this.$message.success(`商品 ${product.productName} 已添加`);
          }
        } else {
          this.$message.error(`未找到商品编码: ${productCode}`);
        }
        // 处理完成后重置扫描仪状态
        this.resetScannerBuffer();
      }).catch((error) => {
        console.error('查询商品失败:', error);
        this.$message.error('查询商品失败');
        // 处理完成后重置扫描仪状态
        this.resetScannerBuffer();
      });
    },
    
    handleWindowFocus() {
      // 窗口获得焦点时的处理
      console.log('窗口获得焦点，扫描仪输入已激活');
    },
    
    handleWindowBlur() {
      // 窗口失去焦点时的处理
      console.log('窗口失去焦点，扫描仪失去监听');
    },
    

    submitted() {
      if (!this.transferTableData.every((item) => item && item.number > 0)) {
        this.$message.error('调拨数量不能为空');
        return;
      }
      this.doSubmit();
      //
    },
    doSubmit() {
      // 你的提交逻辑
      // ...
      transferOrderSave({
        receiptTime: this.receiptTime.getFullYear() + '-' + (this.receiptTime.getMonth() + 1) + '-' + this.receiptTime.getDate(), //得到YYYY-MM-DD
        transferOutStoreId: this.transferOutStoreId[1],
        transferInStoreId: this.transferInStoreId[1],
        transferOutType: this.transferOutType,
        transferInType: this.transferInType,
        remarks: this.remarks,
        transferOrderSkuListRequest: this.transferTableData,
      }).then((res) => {
        // console.log(res);
        this.$message.success('提交成功');
        this.transferTableData = [];
        this.remarks = '';
        this.transferOutStoreId = '';
        this.transferInStoreId = '';
        this.transferOutType = '';
        this.transferInType = '';
        this.showDrawer = false;
        this.productList = [];
        this.selectedCategoryId = '';
      });
    },
    handleTransferOutStoreChange(val) {
      this.transferOutType = val[0];
    },
    handleTransferInStoreChange(val) {
      this.transferInType = val[0];
      if (
        this.transferInType == this.transferOutType &&
        JSON.stringify(this.transferInStoreId) == JSON.stringify(this.transferOutStoreId)
      ) {
        this.$message.error('调出门仓和调入门仓不能相同');
        this.transferInStoreId = '';
        this.$nextTick(() => {
          this.$refs.transferInStore.checkedValue.length = 0;
        });
      }
    },
    addProduct() {
      productCategoryListApi().then((res) => {
        console.log(res);
        this.categoryTree = this.handleTree(res);
      });
      this.fetchProductList();
      this.showDrawer = true;
    },
    // 获取仓库门仓列表
    getStoreList() {
      // 类型(1仓库 2门仓)
      listStore({ type: 1, page: 1, limit: 999 }).then((res) => {
        // this.storeList = res.data;
        console.log(res);
        this.storeList[0].children = res.list;
      });
      listStore({ type: 2, page: 1, limit: 999 }).then((resr) => {
        // this.storeList = res.data;
        console.log(resr);
        this.storeList[1].children = resr.list;
      });
      //组装成树状结构 门仓 仓库 联级选择器
      console.log(this.storeList);
    },
    handleTree(data) {
      // 将平铺的数组转为树结构，el-tree 需要 children 字段
      const idMap = {};
      const tree = [];
      data.forEach((item) => {
        // 适配 el-tree 的 label 字段
        item.label = item.name;
        item.children = [];
        idMap[item.id] = item;
      });
      data.forEach((item) => {
        if (item.pid && idMap[item.pid]) {
          idMap[item.pid].children.push(item);
        } else {
          tree.push(item);
        }
      });
      return tree;
    },
    fetchProductList() {
      const params = {
        categoryId: this.selectedCategoryId,
        limit: this.pageSize,
        page: this.page,
        productName: this.searchKeyword || '',
        transferOutStoreId: this.transferOutStoreId[1],
        transferOutType: this.transferOutType,
        transferInStoreId: this.transferInStoreId[1],
        transferInType: this.transferInType,
      };
      listProductSpec(params).then((res) => {
        console.log(res);
        this.productList = res.list || [];
        this.total = res.total || 0;
      });
    },
    handleSelectionChange(val) {
      this.selectedProducts = val;
    },
    handlePageChange(newPage) {
      this.page = newPage;
      this.fetchProductList();
    },
    handleBatchAdd() {
      this.transferTableData.push(...this.selectedProducts);
      this.showDrawer = false;
      this.selectedProducts = [];
    },
    handleDrawerClose() {
      this.showDrawer = false;
      this.selectedProducts = [];
    },
    handleCategoryClick(node) {
      this.selectedCategoryId = node.id;
      this.page = 1;
      this.fetchProductList();
    },
    handleRowAdd(index) {
      // 可根据业务需求实现行复制
      const row = { ...this.transferTableData[index] };
      this.transferTableData.splice(index + 1, 0, row);
    },
    handleRowRemove(index) {
      this.transferTableData.splice(index, 1);
    },
  },
 
  filters: {
    padIndex(val) {
      return (val + 1).toString().padStart(3, '0');
    },
  },
  computed: {
    transferTableDataWithAdd() {
      // 返回原有数据+添加行
      return [...this.transferTableData];
    },
  },
};
</script>

<style scoped>
.transfer-add-container {
  background: #f5f6fa;
  min-height: 100vh;
  padding: 24px 32px;
}

.store-select-form {
  background: #fff;
  padding: 24px 24px 10px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
  margin-bottom: 24px;
}

.drawer-content-flex {
  display: flex;
  height: 100%;
}

.category-tree-panel {
  width: 220px;
  margin-right: 24px;
  border: 1px solid #e4e7ed;
  background: #fafbfc;
  border-radius: 6px;
  padding: 16px 8px;
  max-height: 80vh;
  overflow-y: auto;
}

.product-list-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.product-list-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.drawer-footer-btns {
  text-align: right;
  margin-top: 18px;
}

::v-deep .el-drawer__body {
  padding: 32px 32px 16px 32px;
}

.transfer-table-wrapper {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
  padding: 18px 24px 24px 24px;
  margin-bottom: 24px;
}

.add-row-cell {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 40px;
}
.add-product-btn {
  color: #409eff;
  border: 1px dashed #409eff;
  background: #f8fbff;
  font-weight: 500;
  border-radius: 4px;
  padding: 0 24px;
  transition: all 0.2s;
}
.add-product-btn:hover {
  background: #ecf5ff;
  border-color: #66b1ff;
  color: #337ecc;
}
</style>
